package com.siyoumi.app.modules.fun.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.entity.FunRecord;
import com.siyoumi.app.modules.fun.service.SvcFun;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.WxAppApiController;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/wxapp/fun/api")
public class ApiFun
        extends WxAppApiController {
    /**
     * 初始化
     */
    @GetMapping("list")
    public XReturn list() {
        SvcFun svcFun = SvcFun.getBean();

        InputData inputData = InputData.fromRequest();
        String yyyyMM = inputData.input("yyyyMM");
        if (XStr.hasAnyText(yyyyMM)) {
            LocalDateTime b = XDate.parse(yyyyMM + "-01");
            LocalDateTime e = XDate.parse(yyyyMM + "-01").plusMonths(1).minusSeconds(1);
            inputData.put("date_begin", XDate.toDateTimeString(b));
            inputData.put("date_end", XDate.toDateTimeString(e));
        }
        inputData.put("uid", getUid());

        String[] select = {
                "funrec_num",
                "funrec_desc",
                "funrec_create_date",
        };
        JoinWrapperPlus<FunRecord> query = svcFun.getQuery(inputData);
        query.select(select);
        query.orderByDesc("funrec_create_date")
                .orderByAsc("funrec_id");

        IPage<FunRecord> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize(), false);
        IPage<Map<String, Object>> pageData = SvcFun.getApp().getMaps(page, query);

        List<Map<String, Object>> list = pageData.getRecords();
        for (Map<String, Object> item : list) {
            FunRecord entity = SvcFun.getApp().loadEntity(item);
            item.put("yyyyMMdd", XDate.toDateString(entity.getFunrec_create_date()));
            item.put("ab_type", entity.getFunrec_num() > 0 ? "+" : "-");
        }

        getR().setData("fun", svcFun.getFun(getUid()));
        getR().setData("list", list);
        getR().setData("setting", svcFun.getSetting());

        return getR();
    }
}
